<template>
  <!-- 场地列表 -->
  <div>
  	<div v-show="mainConState">
    <Header></Header>
    <!--siteList开始-->
    <div class=" w1200 bc mt30 mb70 pr">
      <div class="condition b87  pl20 pr20">
        <table class="condition_tb">
          <col class="w120"/>
          <col class=" w80"/>
          <col class="w880"/>
          <!--地点-->
          <tr class="pr">
            <td class="tr vt pt20"><b class="c7 fm_yahei f14 fb lh150 ">区域&nbsp;&nbsp;&nbsp;&nbsp;</b></td>
            <td class="vt  pt20 bb87_dot" style="cursor: pointer;"><a
              class="inline-block c30 pl10 pr10 ml30 h24 fm_songti f12 lh200 hoverbg_grn curbg_grn" @click="clearCity">全部</a></td>
            <td class="bb87_dot">
              <!-- <a href="#" class="moreBtnUp">收起</a> -->
              <!--<div>-->
              <!--<a v-for="(list,index) in Province" :provinceId="list.id" :Index="index" @click="selectProvince"-->
              <!--:class="{curbg_grn:Active==index}"-->
              <!--class="fl  h24 fm_songti f12 lh200 c30 pl10 pr10 ml30 mt20 hoverbg_grn pointer">{{list.name}}</a>-->
              <!--</div>-->
              <div class="areaBox">
                <el-cascader
                  :options="options"
                  change-on-select
                  :props="optionsProps"
                  @change="selectProvince"
                  :clearable="true"
                ></el-cascader>
              </div>
            </td>
          </tr>
          <!--类型-->
          <tr class="pr">
            <td class="tr vt pt20 "><b class="c7 fm_yahei f14 fb lh150 ">类型&nbsp;&nbsp;&nbsp;&nbsp;</b>
            </td>
            <td class="vt bb87_dot pt20"><a  @click="clickBtn" selId= "0" selType="类型" :class="{curbg_grn: items['typeActive']==='0'}"
                                            class="inline-block pl10 pr10 ml30 h24 fm_songti f12 lh200 hoverbg_grn pointer">全部</a>
            </td>
            <td class="bb87_dot overflow ">
              <!--<a v-show="index==0" class="moreBtnDown" style="width:60px;cursor:pointer;">更多</a>-->
              <div class="fl h44">
                <a v-for="(list,i) in types['typeDetails']" @click="clickBtn" :selId= "list['id']" selType="类型" :class="{curbg_grn: items['typeActive']==list['id']}" class="fl  h24 fm_songti f12 lh200 pl10 pr10 ml30  mt20 hoverbg_grn" style="cursor:pointer;">
                  {{list.typeName}}
                </a>
              </div>
            </td>
          </tr>
          <tr class="pr">
            <td class="tr vt pt20 "><b class="c7 fm_yahei f14 fb lh150 ">标签&nbsp;&nbsp;&nbsp;&nbsp;</b>
            </td>
            <td class="vt bb87_dot pt20">
              <a :class="{curbg_grn: items['tagActive']==='0'}"
                                            class="inline-block pl10 pr10 ml30 h24 fm_songti f12 lh200 hoverbg_grn pointer" @click="clickBtn" selId= "0" selType="标签">全部</a>
            </td>
            <td class="bb87_dot overflow ">
              <!--<a v-show="index==0" class="moreBtnDown" style="width:60px;cursor:pointer;">更多</a>-->
              <div class="fl h44">
                <a v-for="(list,i) in types['tagDetails']" @click="clickBtn" :selId= "list['id']" selType="标签" :class="{curbg_grn: items['tagActive']==list['id']}" class="fl  h24 fm_songti f12 lh200 pl10 pr10 ml30  mt20 hoverbg_grn" style="cursor:pointer;">
                  {{list.typeName}}
                </a>
              </div>
            </td>
          </tr>
          <tr class="pr">
            <td class="tr vt pt20 "><b class="c7 fm_yahei f14 fb lh150 ">难易程度&nbsp;&nbsp;&nbsp;&nbsp;</b>
            </td>
            <td class="vt bb87_dot pt20"><a :class="{curbg_grn: items['diffActive']==='0'}"
                                            class="inline-block pl10 pr10 ml30 h24 fm_songti f12 lh200 hoverbg_grn pointer" selId= "0" selType="难易程度"  @click="clickBtn">全部</a>
            </td>
            <td class="bb87_dot overflow ">
              <!--<a v-show="index==0" class="moreBtnDown" style="width:60px;cursor:pointer;">更多</a>-->
              <div class="fl h44">
                <a v-for="(list,i) in types['difficultyDetails']" @click="clickBtn" :selId= "list['id']" selType="难易程度" :class="{curbg_grn: items['diffActive']==list['id']}" class="fl  h24 fm_songti f12 lh200 pl10 pr10 ml30  mt20 hoverbg_grn" style="cursor:pointer;">
                  {{list.typeName}}
                </a>
              </div>
            </td>
          </tr>
          <!--简易程度-->
          <!-- <tr>
                  <td class="tr vt pt20 "><b class="c7 fm_yahei f14 fb lh150">简易程度&nbsp;&nbsp;&nbsp;&nbsp;</b></td>
                  <td class="vt bb87_dot pt20" ><a class="inline-block c30 pl10 pr10 ml30 h24 fm_songti f12 lh200 hoverbg_grn " href="#">全部</a></td>
                  <td class="bb87_dot" > -->
          <!--第一排 -->
          <!-- <a class="fl  h24 fm_songti f12 lh200 pl10 pr10 ml30 mt20 curbg_grn" href="#">一星</a>
                        <a class="fl  h24 fm_songti f12 lh200 c30 pl10 pr10 ml30 mt20 hoverbg_grn "href="#">二星</a>
                        <a class="fl  h24 fm_songti f12 lh200 c30 pl10 pr10 ml30 mt20 hoverbg_grn " href="#">三星</a>
                        <a class="fl  h24 fm_songti f12 lh200 c30 pl10 pr10 ml30 mt20 hoverbg_grn " href="#">四星</a>
                        <a class="fl  h24 fm_songti f12 lh200 c30 pl10 pr10 ml30 mt20 hoverbg_grn" href="#">五星</a>

                    </td>
                </tr> -->

        </table>
      </div>
      <!--搜索排序-->
      <div class="mt30 mb20  clearfix">
        <a class="fl h36 fm_songti f14 c20 lh36 vm mr40 pointer" :typeId="newId" @click="changeType" :class="{seleClass : sele === 'new'}">最新
        	<img class="ml5 vm" src="../../../static/images/sort-arrow.png"/>
        </a>
        <a class="fl h36 fm_songti f14 c20 lh36 pointer" :typeId="hotId" @click="changeType" :class="{seleClass : sele === 'hot'}">最热
        	<img src="../../../static/images/hot-btn.png"/>
        </a>
        <a @click="goCreateField"
           class="fr h36 fm_songti f14 c50 lh36 b87 bg97 pl20 pr20 editBtnBg hoverborder_grn pointer"><i
          class="inline-block w20 h10"></i>发布场地</a>
        <a @click="searchKey(keyword)" class="fr w60 h36 bg_grn_119c5b mr20 greenBgSearch pointer"></a>
        <input v-model="keyword" @keyup.enter="searchKey(keyword)" class="fr w350 h36 b87 bgfff pl20 pr20  f12 c40 lh36"
               type="text" placeholder="请输入关键字搜索"/>
      </div>
      <!--场地列表-->
      <div class="areaSite " v-if="lists.length>0">
        <li v-for="(list,index) in lists" class="clearfix b87 mt20 hoverborder_orgred" @click="goDetail(index)">
          <img class="fl w350 h230" v-if="list.imgUrl" :src="list.imgUrl.split(',')[0]+'?x-oss-process=image/resize,m_fill,h_230,w_350'"/>
          <dl class="fl w790 h230 ml30  ">
            <dt class="h60 clearfix bb87">
              <b class="f20 lh60 c20 fm_yahei ">{{limitworld(list.placeName,15,'...')}}</b>
              <p class=" fr f14 lh60 vm c40 fm_songti">
                <span>【</span>
                <span>城市：{{list.cityName}}</span>
                <img class="vm" src="../../../static/images/dot-line.png" alt=""/>
                <span>类型：{{list.placeTypeName}}</span>
                <img class="vm" src="../../../static/images/dot-line.png" alt=""/>
                <span>距离：{{initMap(list.lat,list.lng)}}km</span>
                <span>】</span>
              </p>
            </dt>
            <dd class="clearfix f14 lh200 fm_yahei c40 mt10 vm">
							<span><b class="vm">星级：</b>
							<i v-for="(i,index) in 5" :class="{redStar:list.difficulty>index}" class="grayStar ml10"></i>
							</span>
              <span class="ml40"><b class="vm">简易程度：</b>
							<i v-for="(i,index) in 5" :class="{redStar:list.difficulty>index}" class="grayStar ml10"></i>
							</span>
              <span class="fr c60 vm ">已来过<span class="fm c_red_ce2636 mr5 ml5">{{list.userCount}}</span>人</span>
            </dd>
            <dd class=" w790 h60 overflow mt10">
              <p class="f14 fm_songti c50 lh200">{{limitworld((list.summary===null||list.summary==="")?jsonToHtml(list.jsonDescription):list.summary,150,"...")}}</p>
            </dd>
            <dd class="mt10 clearfix">
              <span class="fl f12 lh36 fm_songti c60">更新&nbsp;{{list.addTime.substring(0,10)}}</span>
              <a class="fr pl20 pr20 pt10 pb10 bg_grn_119c5b br2 f12 c100 fm_songti detailMoreBg hoverbg_orgred pointer"  @click="goDetail(index)">查看详情<i
                class="w15 h10 inline-block"></i></a>
            </dd>
          </dl>
        </li>
      </div>
      <div v-else>
        <p class="isNull">
          暂无内容
        </p>
      </div>

      <!--页码-->
      <div class="block">
        <el-pagination
          @current-change="handleCurrentChange"
          :current-page.sync="currentPage"
          :page-size="pageSize"
          layout="total, prev, pager, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </div>
    <!--siteList结束-->
    <Footer></Footer>
  	</div>
    <Loading v-show="loadState"></Loading>
  </div>
</template>
<script>
  import Header from '../../components/header'
  import Footer from '../../components/footer'
  import Loading from '../../components/loading'
  import axios from '../../../config/http'
  import AMap from "AMap"
  export default {
    components: {
      Header,
      Footer,
      Loading
    },
    data() {
      return {
      	newId:0,
      	hotId:1,
        items: {
      	  diffActive:"0",
          typeActive:"0",
          tagActive:"0"
        },
        lists: [],
        Province: [],
        Active: null,
        clicked: [
          {
            'one': true,
            'two': true
          }
        ],
        all: true,
        keyword_: '',
        keyword: '',
        total: 0,
        pageSize: 8,
        currentPage: 0,
        loadState: true,
        mainConState: false,
        provinceId: 0,
        cityId:0,
        placeTypeIDs: "",
        placeTagIDs:"",
        difficulty: 0,
        first: true,
        lastCls: "",
        nowCls: "",
        typeName:"类型",
        diffName:"难易程度",
        tagName:"标签",
        type:0,
        options:[],
        types:{},
        optionsProps:{
          value:"id",
          label:"name",
          children:"data"
        },
        sele:"new"
      }
    },
    methods: {
      // 跳转创建场地
      goCreateField: function () {
        let token = localStorage.getItem("token");
        if(token === "" || token === "undefined" || token === null){
          this.$message.warning("请先登录");
        }else{
          this.$router.push({path: '/field/createField'})
        }
      },
      // jsonToHtml 兼容富文本
      jsonToHtml: function(json){
        let array = json.split('[{').join('').split('}]').join('').split('},{');
        return this.getText(array);
      },
      getText(argument) {
        let txt = "";
        for (let i = 0; i < argument.length; i++) {
          let Item = argument[i].split(',');
          for (let n = 0; n < Item.length; n++) {
            let ItemArr = Item[n].split(':');
            if (ItemArr[0].split("\"").join("") === "title") {
              txt += ItemArr[1].split("\"").join("")
            }
          }
        }
        return txt.replace(/[\\n]/g, "")
      },
      // 获取场地类型和难度
      getfieldList() {
        axios({
          url: "/Place/ListPlaceType",
          method: "post",
          headers: {
            client: "pc"
          }
        }).then(res => {
          this.types = res.data.data;
        });
      },
      editPlace(index){
        let item = this.lists[index].id
        this.$router.push({
          path: '/field/createField',
          query: {
            id:item
          }
        })
      },
      // 获取场地列表
      getfield() {
        axios({
          url: "/Place/GetList",
          method: "post",
          headers: {
            client: "pc"
          },
          data: {
            "type": this.type,
            "placeTypeIDs": this.placeTypeIDs,
            "difficulty": this.difficulty,
            "lng": 0,
            "lat": 0,
            "cityID": this.cityID,
            "pageIndex": this.currentPage - 1,
            "pageSize": this.pageSize,
            "provinceID": this.provinceId,
            "keyword": this.keyword_,
            "keywordsRegionID": "",
            "keywordsCityID": "",
            "keywordsProvinceID": "",
            "keywordsUserID": "",
            "userID": "",
            "clientType": "pc",
            "placeTagIDs":this.placeTagIDs
          }
        }).then(res => {
          this.lists = res.data.data
          this.total = res.data.total
          this.loadState = false
          this.mainConState = true
        });
      },
      // 点击切换选择条件
      clickBtn(e) {
        this.currentPage = 1;
        let thisEle = e.target;
        let id = thisEle.getAttribute("selId");
        let type = thisEle.getAttribute("selType");
        if(type == this.typeName){
          this.placeTypeIDs = id;
          this.items.typeActive = id;
        }else if(type == this.diffName){
        	this.difficulty = id;
          this.items.diffActive = id;
        }else{
          this.items.tagActive = id;
          this.placeTagIDs = id;
        }
        this.loadState = true;
        this.getfield();
      },
      // 获取省份名称
      getProvince() {
        axios({
          url: '/Common/GetArea',
          method: "post",
          headers: {
            client: "pc"
          }
        }).then(res => {
          let listProvince = res.data.data['listProvince'];
          for (let i = 0, j = listProvince.length; i < j; i++){
            let cityList = listProvince[i]['data'];
            for (let n=0,m=cityList.length;n<m;n++){
                delete cityList[n]['data'];
            }
          }
          this.options = listProvince;
        })
      },
      // 选择地点（省份）
      selectProvince(e) {
      	this.currentPage = 1;
        this.provinceId = e[0];
        this.cityID = e[1];
        this.loadState = true;
        this.getfield();
      },
      // Enter到输入页码页面
      handleCurrentChange(val) {
        window.scrollTo(0, 0)
        this.currentPage = val
        this.loadState = true
        this.getfield()
      },
      // 切换最热、最新
      changeType(e){
      	let typeId = e.target.getAttribute("typeId");
      	this.sele = (typeId == 0) ? "new" : "hot";
      	this.type = typeId;
      	this.loadState = true;
      	this.getfield();
      },
      // 所有城市
      clearCity(){
        this.currentPage = 1;
        this.provinceId = 0;
        this.cityID = 0;
        this.loadState = true;
        this.getfield();
      },
      // 搜索对应场地信息
      searchKey() {
        this.currentPage = 1
        this.pageSize = 8
        this.keyword_ = this.keyword
        if (this.keyword_ == '') {
          this.pageSize = 8
        }
        this.loadState = true
        this.getfield()
      },
      // 点击列表，跳转详情
      goDetail(index) {
        let item = this.lists[index].id
        this.$router.push({
          path: '/filedDetail',
          query: {
            id: item
          }
        })
      },
      computeDistance(startCoords,destCoords){
        var startLatRads = this.degreesToRadians(startCoords.latitude);
        var startLoingRads = this.degreesToRadians(startCoords.longitude);
        var destLatRads = this.degreesToRadians(destCoords.latitude);
        var destLongRads = this.degreesToRadians(destCoords.longitude);
        var Radius = 6371; //radius of the Earth in km
        var distance = Math.acos(Math.sin(startLatRads) * Math.sin(destLatRads) + Math.cos(startLatRads) * Math.cos(destLatRads) * Math.cos(startLoingRads - destLongRads)) * Radius;
        return distance;
   	 	},
   	 	degreesToRadians(degrees){
	        var radians = (degrees * Math.PI) / 180;
	        return radians;
	    },
	    initMap(lat,lng){
      	var startCoords = {
	        latitude: localStorage.getItem("lat"),
	        longitude:localStorage.getItem("lng")
		    };
		    var destCoords = {
		        latitude: lat,
		        longitude:lng
		    };
		    var km = this.computeDistance(startCoords,destCoords);
		    return Math.floor(km);
      },
      // 限制显示字数
      limitworld: function (worlds, wordlength, mark) {
        var nowLength = worlds.length;
        var newWorlds = "";
        if (nowLength > wordlength) {
          newWorlds = worlds.substr(0, wordlength) + mark;
        } else {
          newWorlds = worlds;
        }
        return newWorlds;
      },
      // 定位当前位置
      GeoLocation(){
        AMap.plugin('AMap.Geolocation', function() {
          var geolocation = new AMap.Geolocation({
            // 是否使用高精度定位，默认：true
            enableHighAccuracy: true,
            // 设置定位超时时间，默认：无穷大
            timeout: 10000,
            // 定位按钮的停靠位置的偏移量，默认：Pixel(10, 20)
            buttonOffset: new AMap.Pixel(10, 20),
            //  定位成功后调整地图视野范围使定位位置及精度范围视野内可见，默认：false
            zoomToAccuracy: true,
            //  定位按钮的排放位置,  RB表示右下
            buttonPosition: 'RB'
          });

          geolocation.getCurrentPosition()
          AMap.event.addListener(geolocation, 'complete', onComplete)
          AMap.event.addListener(geolocation, 'error', onError)

          function onComplete (data) {
            if(data.status===1){
                localStorage.setItem("lat",data.position.lat);
                localStorage.setItem("lng",data.position.lng);
            }
          }

          function onError (data) {
            console.log(data);
          }
        })
      }

    },
    mounted() {
      this.GeoLocation();
	    this.getfieldList();
	    this.getfield();
	    this.getProvince();
    }
  }
</script>
<style lang="less" scoped>
  .pointer {
    cursor: pointer;
  }

  .main {
    width: 86%;
    margin: 20px auto;
  }

  .el-main {
    padding: 0;
    margin-left: 20px;
  }

  dl {
    text-align: left;
  }

  dl .redStar {
    background: url(../../../static/images/star-red.png) no-repeat center;
  }

  //重置分页样式
  .el-pager /deep/ .number {
    display: inline-block;

    line-height: 100%;
    border: 1px solid red;
  }

  .el-pagination {
    margin-top: 30px;
    text-align: right;
  }

  .el-pager > li {
    height: auto;
    padding: 10px 10px;
  }

  .isNull {
    width: 100%;
    height: 60px;
    line-height: 60px;
    border-top: 1px solid #E0E0E0;
    border-bottom: 1px solid #E0E0E0;
  }
  .areaBox{
    margin-top: 15px;
    float: left;
    margin-left: 30px;
  }
  .seleClass{
    color:#F60606;
  }
</style>
